﻿using Microsoft.AspNetCore.Http; 
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;

namespace ServiceCore.Tool.Pic
{
    public interface IUpload_Helper
    {
        ResultObjModel UploadPicFile(IFormFileCollection files, string WebRootPath);
        Task<ResultObjModel> UploadPicFileToAsync(IFormFileCollection files, string WebRootPath);
        Task<object> UploadPicFileToAsyncForwangeditor3(IFormFileCollection files, string WebRootPath);
    }
    public class Upload_Helper: IUpload_Helper
    {
        private readonly ISnowflake_Helper _snowflake;
        private readonly IConfiguration AppSettingConfig;

        public Upload_Helper(ISnowflake_Helper snowflake, IConfiguration configuration)
        {
            _snowflake = snowflake;
            AppSettingConfig = configuration;
        }
        public string Uploadurl { get { return AppSettingConfig["Upload:url"]; } }
        public string Pichost { get { return AppSettingConfig["PicHost"]; } }
        public ResultObjModel UploadPicFile(IFormFileCollection files, string WebRootPath)
        {
            ResultObjModel result = new ResultObjModel();
            try
            {
                if (files.Count <= 0)
                {
                    result.code = 1;
                    result.msg = "未检测到任何文件";
                    return result;
                }
                string imgPath = @"/UploadFiles/picture/" + DateTime.Now.ToString("yyyMMdd") + "/";
                string dicPath = WebRootPath + imgPath;
                if (!Directory.Exists(dicPath))
                {
                    Directory.CreateDirectory(dicPath);
                }
                List<object> resultList = new List<object>();
                int i = 0;
                foreach (var item in files)
                {
                    try
                    {
                        var img = item;
                        if (img == null)
                        {
                            resultList.Add(new { posiont = i, state = 1, des = "上传失败=>未能获取图片", url = "" });
                            continue;
                        } 
                        string ext = Path.GetExtension(img.FileName);
                        //判断后缀是否是图片
                        const string fileFilt = ".jpg|.jpeg|.png|.bmp|.gif|.svg|.tif";
                        //判断后缀是否是图片
                        if (ext == null)
                        {
                            resultList.Add(new { posiont = i, state = 1, des = "上传失败=>上传文件没有后缀名", url = "" });
                            continue;
                        }
                        if (fileFilt.IndexOf(ext.ToLower(), StringComparison.Ordinal) <= -1)
                        { 
                            resultList.Add(new { posiont = i, state = 1, des = "上传失败=>上传文件格式必须为图片格式", url = "" });
                            continue;
                        }
                        string fileName = _snowflake.IGet_SnowFlake_Id + "_" + img.FileName;
                        string filePath = Path.Combine(dicPath, fileName);
                        using (FileStream fs = System.IO.File.Create(filePath))
                        {
                            img.CopyTo(fs);
                            fs.Flush();
                        }
                        resultList.Add(new { posiont = i, state = 0, des = "success", url = Pichost + imgPath + fileName });
                    }
                    catch (Exception ex)
                    {
                        resultList.Add(new { posiont = i, state = 1, des = ex.Message, url = "" });
                    }
                    finally {
                        i++;
                    } 
                }
                result.code = 0;
                result.msg = "Success";
                result.data = resultList;
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.msg = "上传失败=>" + ex.Message;
                return result;
            }
            return result;
        }

        public async Task<ResultObjModel> UploadPicFileToAsync(IFormFileCollection files, string WebRootPath)
        {
            ResultObjModel result = new ResultObjModel();
            try
            {
                if (files.Count <= 0)
                {
                    result.code = 1;
                    result.msg = "未检测到任何文件";
                    return result;
                }
                string imgPath = @"/UploadFiles/picture/" + DateTime.Now.ToString("yyyMMdd") + "/";
                string dicPath = WebRootPath + imgPath;
                if (!Directory.Exists(dicPath))
                {
                    Directory.CreateDirectory(dicPath);
                }
                List<object> resultList = new List<object>();
                int i = 0;
                foreach (var item in files)
                {
                    try
                    {
                        var img = item;
                        if (img == null)
                        {
                            resultList.Add(new { posiont = i, state = 1, des = "上传失败=>未能获取图片", url = "" });
                            continue;
                        }
                        string ext = Path.GetExtension(img.FileName);
                        //判断后缀是否是图片
                        const string fileFilt = ".jpg|.jpeg|.png|.bmp|.gif|.svg|.tif";
                        //判断后缀是否是图片
                        if (ext == null)
                        {
                            resultList.Add(new { posiont = i, state = 1, des = "上传失败=>上传文件没有后缀名", url = "" });
                            continue;
                        }
                        if (fileFilt.IndexOf(ext.ToLower(), StringComparison.Ordinal) <= -1)
                        {
                            resultList.Add(new { posiont = i, state = 1, des = "上传失败=>上传文件格式必须为图片格式", url = "" });
                            continue;
                        }
                        string fileName = _snowflake.IGet_SnowFlake_Id + "_" + img.FileName;
                        string filePath = Path.Combine(dicPath, fileName);
                        using (FileStream fs = System.IO.File.Create(filePath))
                        {
                            await img.CopyToAsync(fs); 
                            fs.Flush();
                        }
                        resultList.Add(new { posiont = i, state = 0, des = "success", url = Pichost + imgPath + fileName });
                    }
                    catch (Exception ex)
                    {
                        resultList.Add(new { posiont = i, state = 1, des = ex.Message, url = "" });
                    }
                    finally
                    {
                        i++;
                    }
                }
                result.code = 0;
                result.msg = "Success";
                result.data = resultList;
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.msg = "上传失败=>" + ex.Message;
                return result;
            }
            return result;
        }

        /// <summary>
        /// for富文本编辑器
        /// </summary>
        /// <param name="files"></param>
        /// <param name="WebRootPath"></param>
        /// <returns></returns>
        public async Task<object> UploadPicFileToAsyncForwangeditor3(IFormFileCollection files, string WebRootPath)
        {
            object result = new object();
            try
            {
                if (files.Count <= 0)
                {
                    return new { errno = 1, msg = "未检测到任何文件" };
                }
                string imgPath = @"/UploadFiles/picture/" + DateTime.Now.ToString("yyyMMdd") + "/";
                string dicPath = WebRootPath + imgPath;
                if (!Directory.Exists(dicPath))
                {
                    Directory.CreateDirectory(dicPath);
                }
                List<string> urllist = new List<string>(); 
                foreach (var item in files)
                {
                    try
                    {
                        var img = item;

                        string ext = Path.GetExtension(img.FileName);
                        //判断后缀是否是图片
                        //const string fileFilt = ".jpg|.jpeg|.png|.bmp|.gif|.svg|.tif";  
                        string fileName = _snowflake.IGet_SnowFlake_Id + "_" + img.FileName;
                        string filePath = Path.Combine(dicPath, fileName);
                        using (FileStream fs = System.IO.File.Create(filePath))
                        {
                            await img.CopyToAsync(fs);
                            fs.Flush();
                        }
                        urllist.Add(Pichost + imgPath + fileName);
                    }
                    catch (Exception ex)
                    {
                    }
                }  
                return new { errno = 0, msg = "success", data = urllist.ToArray() };
            }
            catch (Exception ex)
            { 
                return new { errno = 1, msg = "上传失败=>" + ex.Message };
            } 
        }
    }
}
